
//
//  VERealNameViewController.m
//  VEMoneyPorject
//
//  Created by BlueWind on 2018/9/27.
//  Copyright © 2018年 陈建. All rights reserved.
//

#import "VERealNameViewController.h"
#import "VERealNameTextTableViewCell.h"
#import "VERealNameImageTableViewCell.h"

#import <TZImageManager.h>
#import <TZVideoPlayerController.h>
#import <TZPhotoPreviewController.h>
#import <TZGifPhotoPreviewController.h>
#import <TZImagePickerController.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "DTLongButtonView.h"

@interface VERealNameViewController ()

{
    BOOL _isCard; /**<是否是身份证*/
    NSString *_cardStr;
    NSString *_nameStr;
    NSString *_numStr;
    NSString *_isValid;
    NSString *_timeStr;
    
    
    UIImage *_image1;
    UIImage *_image2;
    UIImage *_image3;
    
    NSInteger _seletedWhichRow;
    
    BRTextField *_nameText;
    
    BRTextField *_numText;
    
}

@property (nonatomic, strong)NSMutableArray *marray;

@property (nonatomic, strong)NSMutableArray *imageArr;

@property (nonatomic, strong) UIImagePickerController *imagePickerVc;

@end

@implementation VERealNameViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.marray = [NSMutableArray new];
    self.navItemTitle = @"实名认证";
    self.isSuccessNet = YES;

    
    self.imageArr = [NSMutableArray arrayWithArray:@[[UIImage imageNamed:@"1"],[UIImage imageNamed:@"2"],[UIImage imageNamed:@"3"]]];
    

}

- (NSInteger)cj_numberOfSections {
    return 2;
}

/**
 某个cell的数量
 */
- (NSInteger)cj_numberOfRowsInsection:(NSInteger)section {
    
    if (section == 0) {
        if (_isCard == YES) {
            return 5;
        } else {
            return 3;
        }
    } else if (section == 1) {
        if (_isCard == YES) {
            return 3;
        } else {
            return 2;
        }
    } else {
        return 1;
    }
    
}

- (CGFloat)cj_cellHeightAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return 50;
    } else if (indexPath.section == 1) {
        return 200;
    } else {
        return 0;
    }
    
}
- (CGFloat)cj_sectionFooterHeightAtSection:(NSInteger)section{
    if (section == 1) {
        return 100;
    }else{
        return 0;
    }
    
}

- (UIView *)cj_footerAtSection:(NSInteger)section{
    if (section == 1) {
        DTLongButtonView *view = [DTLongButtonView shareView];
        [view.tapBtn setTitle:@"提交" forState:UIControlStateNormal];
        view.tapBtnBlock = ^{
            NSLog(@"确 定");
            
            [self commit];
            
        };
        return view;
    }
    return nil;
}



- (void)commit {
    
    
    NSString *nameT = [_nameText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString *numT = [_numText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSDictionary *dic = [NSDictionary new];
    NSString *userId = [[CJUserInfoManager sharedManager] currentUserInfo].USERID;
    NSMutableArray *marr = [NSMutableArray new];
    if (_isCard == YES) {
        
        if ([BHJProjectHelper isNilOrNull:_cardStr] || [BHJProjectHelper isNilOrNull:nameT] || [BHJProjectHelper isNilOrNull:numT] || [BHJProjectHelper isNilOrNull:_isValid] || [BHJProjectHelper isNilOrNull:_timeStr]) {
            return [CJUIKit showErrorWithStatus:@"请完整填写信息"];
        }
        
        if ([BHJProjectHelper isNilOrNull:_image1] || [BHJProjectHelper isNilOrNull:_image2] || [BHJProjectHelper isNilOrNull:_image3]) {
            return [CJUIKit showErrorWithStatus:@"请完整选择图片"];
        }
        dic = @{
                @"userid": userId,
                @"paptype": _cardStr,
                @"papname": nameT,
                @"papno": numT,
                @"papstate": [_isValid isEqualToString:@"是"] ? @"1" : @"0",
                @"paptime": _timeStr,
                };
        NSData *imageData1 = UIImageJPEGRepresentation(_image1, 0.8);
        [marr addObject:imageData1];
        NSData *imageData2 = UIImageJPEGRepresentation(_image2, 0.8);
        [marr addObject:imageData2];
        NSData *imageData3 = UIImageJPEGRepresentation(_image3, 0.8);
        [marr addObject:imageData3];
        
        
    } else {
        if ([BHJProjectHelper isNilOrNull:_cardStr] || [BHJProjectHelper isNilOrNull:nameT] || [BHJProjectHelper isNilOrNull:numT]) {
            return [CJUIKit showErrorWithStatus:@"请完整填写信息"];
        }
        
        if ([BHJProjectHelper isNilOrNull:_image1] || [BHJProjectHelper isNilOrNull:_image2]) {
            return [CJUIKit showErrorWithStatus:@"请完整选择图片"];
        }
        dic = @{
                @"userid": userId,
                @"paptype": _cardStr,
                @"papname": nameT,
                @"papno": numT,
                @"papstate": @"",
                @"paptime":@"",
                };
        NSData *imageData1 = UIImageJPEGRepresentation(_image1, 0.8);
        [marr addObject:imageData1];
        NSData *imageData2 = UIImageJPEGRepresentation(_image2, 0.8);
        [marr addObject:imageData2];
    }
    

    NSString *path = [NSString stringWithFormat:@"%@/VEService/UploadRenzheng.do",kPublicInterfaceAPI];
    CJBaseRequest *request = [CJBaseRequest cj_requestWithUrl:path isPost:YES withParameters:dic];
    request.cj_imageArray =  marr;
    [request cj_sendRequestWithCompletion:^(id response, BOOL success, NSString *message) {
        
        NSLog(@"%@",response);
        [CJUIKit showSuccessWithStatus:message];
       
        UserInfoModel *model = [CJUserInfoManager sharedManager].currentUserInfo;
        model.STATE = @"待审核";
        [[CJUserInfoManager sharedManager] resetUserInfoWithUserInfo:model];
        if (self.DataSuccessBlock) {
            self.DataSuccessBlock();
        }
    }];
}


/**
 某行的cell
 */
- (CJBaseTableViewCell *)cj_cellAtIndexPath:(NSIndexPath *)indexPath {
    
    NSArray *arr = @[@"证件类型",@"证件姓名",@"证件号码",@"证件是否永久有效",@"证件有效日期"];
    
    if (indexPath.section == 0) {
        VERealNameTextTableViewCell *cell = [VERealNameTextTableViewCell cellWithTableView:self.tableView];
        cell.textNew.placeholder = arr[indexPath.row];
        
        if (indexPath.row == 0) {
            cell.jiantou.hidden = NO;
            
            cell.textNew.text = _cardStr;
            cell.textNew.userInteractionEnabled = NO;
            
        } else if (indexPath.row == 1) {
            cell.jiantou.hidden = YES;
            _nameText = cell.textNew;
            cell.textNew.userInteractionEnabled = YES;
        } else if (indexPath.row == 2) {
            cell.jiantou.hidden = YES;
            _numText = cell.textNew;
            cell.textNew.userInteractionEnabled = YES;
        } else if (indexPath.row == 3) {
            cell.jiantou.hidden = NO;
            cell.textNew.userInteractionEnabled = NO;

        } else if (indexPath.row == 4) {
            cell.jiantou.hidden = NO;
            cell.textNew.userInteractionEnabled = NO;

        }
        
        return cell;
    } else if (indexPath.section == 1) {

        
        NSArray *titleArr = @[@"证件正面",@"证件反面",@"上传手持证件照片"];
        
        VERealNameImageTableViewCell *cell = [VERealNameImageTableViewCell cellWithTableView:self.tableView];
        cell.imageViews.image = self.imageArr[indexPath.row];
        cell.remandLab.text = titleArr[indexPath.row];
        return cell;
    } else {

       
        return nil;
    }
}

- (void)cj_didSelectCellAtIndexPath:(NSIndexPath *)indexPath cell:(CJBaseTableViewCell *)cell {
    

    if (indexPath.section == 0) {
        
        WEAKSELF
        VERealNameTextTableViewCell *celll = [self.tableView cellForRowAtIndexPath:indexPath];
        __weak typeof(celll) weakCell = celll;
        if (indexPath.row == 0) {
            [BRStringPickerView showStringPickerWithTitle:@""
                                               dataSource:@[@"身份证", @"港澳来往大陆通行证",@"台湾来往大陆通行证",@"护照"]
                                          defaultSelValue:@"身份证"
                                              resultBlock:^(id selectValue) {
                                                  if ([selectValue isEqualToString:@"身份证"]) {
                                                      self->_isCard = YES;
                                                  } else {
                                                      self->_isCard = NO;
                                                  }
                                                  
                                                  weakCell.textNew.text = selectValue;
                                                  self->_cardStr = selectValue;
                                                  [weakSelf.tableView reloadData];
                                              }];
        } else if (indexPath.row == 3) {
            [BRStringPickerView showStringPickerWithTitle:@""
                                               dataSource:@[@"是", @"否"]
                                          defaultSelValue:@""
                                              resultBlock:^(id selectValue) {
                                                  weakCell.textNew.text = selectValue;
                                                  self->_isValid = selectValue;
                                              }];
        } else if (indexPath.row == 4) {
            [BRDatePickerView showDatePickerWithTitle:@"证件截止时间"
                                             dateType:UIDatePickerModeDate
                                      defaultSelValue:@""
                                           minDateStr:nil
                                           maxDateStr:@""
                                         isAutoSelect:YES
                                           themeColor:nil
                                          resultBlock:^(NSString *selectValue) {
                                              weakCell.textNew.text = selectValue;
                                              self->_timeStr = selectValue;
                                          } cancelBlock:^{
                                              NSLog(@"点击了背景或取消按钮");
                                          }];
        }
        
        
    }
    
    
    
    if (indexPath.section == 1) {
        _seletedWhichRow = indexPath.row;
        [self choiceImg];
    }
}


#pragma mark - 选中上传图片
- (void)choiceImg
{
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:0 handler:^(UIAlertAction * _Nonnull action) {
        [self pushImagePickerController];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"相机" style:0 handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = self.navigationController.navigationBar.barTintColor;
        _imagePickerVc.navigationBar.tintColor = self.navigationController.navigationBar.tintColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
        BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
    }
    return _imagePickerVc;
}
#pragma mark - 拍照
- (void)takePhoto {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied)) {
        // 无相机权限 做一个友好的提示
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"无法使用相机" message:@"请在iPhone的""设置-隐私-相机""中允许访问相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
        alert.delegate = self;
        [alert show];
        // 拍照之前还需要检查相册权限
    }
    //    else if ([TZImageManager authorizationStatus] == 0) { // 正在弹框询问用户是否允许访问相册，监听权限状态
    //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //            return [self takePhoto];
    //        });
    //    }
    else { // 调用相机
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            self.imagePickerVc.sourceType = sourceType;
            _imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            
            [self presentViewController:_imagePickerVc animated:YES completion:nil];
        } else {
            NSLog(@"模拟器中无法打开照相机,请在真机中使用");
        }
    }
}


#pragma mark - 选择照片
- (void)pushImagePickerController {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:3 delegate:self pushPhotoPickerVc:YES];
    
#pragma mark - 四类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = NO;
    imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
    
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.allowPickingGif = NO;
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    
    /// 5. 单选模式,maxImagesCount为1时才生效
    imagePickerVc.showSelectBtn = YES;
    imagePickerVc.allowCrop = NO;
    imagePickerVc.needCircleCrop = NO;
    imagePickerVc.circleCropRadius = 100;
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        //        [_selectedAssets addObject:assetModel.asset];
        
        if (_seletedWhichRow == 0) {
            _image1 = image;
        } else if (_seletedWhichRow == 1) {
            _image2 = image;
        } else {
            _image3 = image;
        }
        
        [self.imageArr replaceObjectAtIndex:_seletedWhichRow withObject:image];
        
        [self.tableView reloadData];
        
    }
}

#pragma mark - TZImagePickerControllerDelegate

// 这个照片选择器会自己dismiss，当选择器dismiss的时候，会执行下面的代理方法
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    
    UIImage *image = photos[0];
    
    if (_seletedWhichRow == 0) {
        _image1 = image;
    } else if (_seletedWhichRow == 1) {
        _image2 = image;
    } else {
        _image3 = image;
    }
    [self.imageArr replaceObjectAtIndex:_seletedWhichRow withObject:image];
    [self.tableView reloadData];
    
}



@end
